package com.nf.teamwork.mall.filter;

import com.nf.teamwork.mall.entity.UserInf;
import com.nf.teamwork.mall.utils.JwtUtil;
import com.nf.teamwork.mall.utils.PayLoad;
import com.nf.teamwork.mall.utils.RsaKeyProperties;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: LJP
 * @Classname JwtVerifyFilter
 * @Date: 2020-02-29 19:15
 * @Description: 验证token是否正确的过滤器
 */
public class JwtVerifyFilter extends BasicAuthenticationFilter {
    private RsaKeyProperties prop;

    public JwtVerifyFilter(AuthenticationManager authenticationManager, RsaKeyProperties properties) {
        super(authenticationManager);
        this.prop = properties;
    }

    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        /*获取头部为Authorization的相关信息，签发JWT的时候就是写在这个地方*/
        String header = request.getHeader("Authorization");

        /*下面可以通过头信息判断用户是否可以进行下一步认证*/
        if (header == null || !header.startsWith("Basic ")) {
            /*携带的token格式错误，不做token的解析直接交给下一条过滤链执行*/
            chain.doFilter(request, response);
        } else {
            /*携带的token格式正确*/
            /*下面对token进行验证,先得到token*/
            String token = header.replace("Basic ", "");
            /*验证是否正确,并得到载荷部分信息*/
            PayLoad<UserInf> payLoad = JwtUtil.getInfoFromToken(token, prop.getPublicKey(), UserInf.class);
            /*获取到载荷部分用户对象信息*/
            UserInf userEntity = payLoad.getUserInfo();
            if(userEntity != null){
                UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(userEntity.getUsername(), null, userEntity.getAuthorities());
                /*获取到当前用户的登录信息，并将信息放入到当前的session中，用于做后期的权限控制操作*/
                SecurityContextHolder.getContext().setAuthentication(authRequest);
                chain.doFilter(request, response);
            }
        }
    }
}
